﻿namespace Away.Common.Mvc.Auth;

/// <summary>
/// 权限过滤
/// </summary>
public class AuthAttribute : ServiceFilterAttribute
{
    public AuthAttribute() : base(typeof(JwtAuthorizationFilter))
    {
    }
}

[ServiceInject(ServiceLifetime.Scoped, true)]
public class JwtAuthorizationFilter : IAsyncAuthorizationFilter
{
    private readonly ICommandSender _sender;
    public JwtAuthorizationFilter(ICommandSender sender)
    {
        _sender = sender;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        if (context.ActionDescriptor is not ControllerActionDescriptor controllerType || controllerType.ControllerTypeInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any())
        {
            return;
        }

        if (controllerType.EndpointMetadata.Any(o => o is AllowAnonymousAttribute))
        {
            return;
        }

        var userId = context.HttpContext.User.Claims.FirstOrDefault(o => o.Type == JwtClaimNames.Uid)?.Value;
        if (userId == null)
        {
            context.Result = ApiResult.Ok(403, "没有该权限");
            return;
        }

        var data = await _sender.Send(new AuthCmd
        {
            AdminId = Convert.ToInt32(userId),
            Method = context.HttpContext.Request.Method,
            Url = context.HttpContext.Request.Path
        });

        if (!data.Success)
        {
            context.Result = data;
        }
    }
}